package cn.edu.sdjzu.xg2103.dao;

import cn.edu.sdjzu.xg2103.controller.helper.JdbcHelper;
import cn.edu.sdjzu.xg2103.entity.*;

import cn.edu.sdjzu.xg2103.entity.Condition;
import cn.edu.sdjzu.xg2103.entity.Pagination;
import cn.edu.sdjzu.xg2103.entity.Teacher;
import cn.edu.sdjzu.xg2103.exception.BysjException;
import cn.edu.sdjzu.xg2103.service.DepartmentService;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;


public class TeacherDao {
    public Collection<Teacher> findAll(Connection connection, List<Condition> conditionlist, Pagination pagination) throws SQLException {
        Collection<Teacher> desiredTeachers = new HashSet<Teacher>();
        //准备预编译的语句
        StringBuilder sql_select = new StringBuilder("SELECT * FROM teacher");
        if(conditionlist!=null){
            String whereClause = Condition.toWhereClause(conditionlist);
            sql_select.append(whereClause);
        }

        int totalNum = CommonDao.getInstance().count(connection,"teacher",conditionlist);
        String pginationClause = pagination.toLimitClause(totalNum);
        sql_select.append(pginationClause);
        PreparedStatement pstmt_select_all = connection.prepareStatement(sql_select.toString());
        //执行预编译语句，结果集保存在resultSet中
        ResultSet resultSet_select_all = pstmt_select_all.executeQuery();
        //遍历resultSet
        while (resultSet_select_all.next()) {
            int id = resultSet_select_all.getInt("id");
            String name = resultSet_select_all.getString("name");
            String no = resultSet_select_all.getString("no");
            int department_id = resultSet_select_all.getInt("department_id");
            Department department = DepartmentService.getInstance().find(department_id);
            Teacher teacher = new Teacher(id, name, no,department,department_id);
            desiredTeachers.add(teacher);
        }
        JdbcHelper.close(resultSet_select_all,pstmt_select_all,connection);
        return desiredTeachers;
    }
    public boolean update(Connection connection,Teacher teacher) throws SQLException, BysjException {
        //获取数据库连接
        //准备预编译的语句
        String sql_update = "update teacher " +
                "set name=? where id=1";
        PreparedStatement pstmt_insert = connection.prepareStatement(sql_update);
        pstmt_insert.setString(1,teacher.getName());
        //执行预编译语句，影响的行数保存在rowAffected中
        int rowAffected = pstmt_insert.executeUpdate();
        return rowAffected > 0;
    }
    private static final TeacherDao teacherDao =new TeacherDao();
    public static TeacherDao getInstance() {
        return teacherDao;
    }
    private static Collection<Teacher> teachers;
    private TeacherDao(){}

}
